import axios from 'axios'
import store from '@/store'
import { Message } from 'element-ui'
const service = axios.create({
  baseURL: 'https://likede2-java.itheima.net/api',
  timeout: 5000
})
const timeOut = 7200
service.interceptors.request.use(
  (config) => {
    const loginTime = store.getters.loginTime
    if (loginTime) {
      const curTime = Date.now()
      const gap = (curTime - loginTime) / 1000
      if (gap > timeOut) {
        Message.error('登录超时，请重新登录')
        store.dispatch('user/logout')
      }
    }
    // 注入token
    (store.getters.token) && (config.headers['Authorization'] = `${store.getters.token}`)
    return config
  },
  err => {
    throw Error(err)
  }
)

service.interceptors.response.use(
  (response) => {
    return response.data
  },
  err => {
    if (err.response.status === 401) {
      Message.error('登录超时，请重新登录')
      store.dispatch('user/logout')
    }
    throw Error(err)
  }
)

export default service
